package top.usts.springframework.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import top.usts.springframework.beans.BeansException;
import top.usts.springframework.beans.factory.DisposableBean;

import java.lang.reflect.Method;

/**
 * @description:
 * @author: CJ
 * Adapter that implements the {@link DisposableBean} and {@link Runnable} interfaces
 * performing various destruction steps on a given bean instance:
 *
 *
 * 销毁适配器
 * @date: 2022/2/24
 */
public class DisposableBeanAdapter implements DisposableBean {
    private final Object bean;
    private final String beanName;
    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, String destroyMethodName) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = destroyMethodName;
    }

    @Override
    public void destroy() throws Exception {
        // 1 实现接口 DisposableBean
        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
        }

        // 2 注解配置 destroy-method  判断是避免二次执行销毁
        //这里限制destroy 为啥？？
        if (StrUtil.isNotBlank(destroyMethodName) && !(bean instanceof DisposableBean && "destroy".equals(this.destroyMethodName))) {
            Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
            if (null == destroyMethod) {
                throw new BeansException("could't find a destroy method named '" + destroyMethodName + "' on bean with name '" + beanName+"'");
            }
            destroyMethod.invoke(bean);
        }

    }
}
